using System.Windows;
using System.Windows.Input;
using LibVLCSharp.Shared;
using MahApps.Metro.Controls;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using vlcplay.ViewModels;

namespace vlcplay
{
    public partial class MaximizedVideoWindow : MetroWindow
    {
        private readonly ILogger<MaximizedVideoWindow>? _logger; // Allow logger to be nullable
        public VideoItemViewModel? VideoItem { get; private set; }

        public MaximizedVideoWindow() // For XAML designer
        {
            InitializeComponent();
            if (Application.Current is App app && App.ServiceProvider != null)
            {
                _logger = App.ServiceProvider.GetRequiredService<ILogger<MaximizedVideoWindow>>();
            }
            else
            {
                // Fallback or throw if logger is critical and ServiceProvider isn't ready
                // This path should ideally not be hit in a running application.
                // Consider _logger = new NullLogger<MaximizedVideoWindow>(); if you have a NullLogger pattern
            }
        }

        public MaximizedVideoWindow(VideoItemViewModel videoItemVM, ILogger<MaximizedVideoWindow> logger)
        {
            InitializeComponent();
            _logger = logger;
            VideoItem = videoItemVM;
            DataContext = VideoItem;
        }

        private void MaximizedVideoWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (VideoItem != null)
            {
                VideoItem.EnsureMediaPlayer(); // Ensure MediaPlayer is created
                MaximizedPlayerVideoView.MediaPlayer = VideoItem.MediaPlayer;
                VideoItem.IsVideoViewLoaded = true; // Mark as loaded for this view
                _logger?.LogInformation($"MaximizedVideoWindow: MediaPlayer assigned for {VideoItem.Device}_{VideoItem.Channel}. Attempting to play.");
                // Automatically try to play
                if (VideoItem.PlayVideoCommand.CanExecute(null))
                {
                    _ = VideoItem.PlayVideoCommand.ExecuteAsync(null);
                }
            }
        }

        private void MaximizedVideoWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _logger?.LogInformation($"MaximizedVideoWindow closing for {VideoItem?.Device}_{VideoItem?.Channel}.");
            VideoItem?.StopVideoCommand.Execute(null);
            MaximizedPlayerVideoView.MediaPlayer = null; // Detach MediaPlayer
            VideoItem?.IsVideoViewLoaded_Set(false); // Reset loaded state if you add such a setter
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void MaximizedVideoWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }
    }
}